package com.zzty.txj1.util;


import com.zzty.txj1.entity.*;
import com.zzty.txj1.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description: 构建执行定时任务www.fhadmin.org
 * Designer: jack
 * Date: 2017/8/10
 * Version: 1.0.0
 */
@Component
public class ScheduledUtil {
    @Value("${event[]}")
    private String[] event;
    @Value("${event1[]}")
    private String[] event1;
    @Autowired
    private DoEventService doEventService;
    @Autowired
    private UserEventsService userEventsService;
    @Autowired
    private EventService eventService;
    @Autowired
    private AbilityService abilityService;
    @Autowired
    private UserService userService;
    @Autowired
    private  ClazzService clazzService;
    private Logger logger = LoggerFactory.getLogger(ScheduledUtil.class);

    @Scheduled(cron = "0 0 2 ? * MON,WED,FRI,SAT,SUN")  //cron接受cron表达式，根据cron表达式确定定时规则
    public void initDoEvent() {
        Date date = new Date();
        DoEvent doEvent = new DoEvent();
        SplitUtil split = new SplitUtil();
        List<UserEvents> userEventsList = userEventsService.getAllUserEvents();
        logger.info("===initialDelay:userEventsList " + userEventsList);
        for (UserEvents userEvents : userEventsList) {
            Integer userId = userEvents.getUserId();
            List<Integer> ss = split.getSplit(userEvents.getEventId());
            for (Integer s : ss) {
                doEvent.setUserId(userId);
                doEvent.setEventId(s);
                doEvent.setResult(-1);
                doEvent.setDate(date);
                doEventService.initDoEvent(doEvent);
                logger.info("===initialDelay:初始化数据 " + s + ":成功");

            }
        }
    }

    @Scheduled(cron = "0 0 22 ? * MON,WED,FRI,SAT,SUN")
    public void updateDoEvent() {
        Date date1 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(date1);
        java.sql.Date sqlDate = java.sql.Date.valueOf(date);//java util Date 转换为 java sql Date

        SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
        String week = dateFm.format(date1);//转换时间格式为星期几
        logger.info("===initialDelay:week is " + week);

        List<Integer> userIdList = userEventsService.getAllUserId();
        logger.info("===initialDelay: userIdList is " + userIdList);
        for (Integer userId : userIdList) {
            try {
                DoEvent doEvent = new DoEvent();
                doEvent.setDate(sqlDate);
                doEvent.setUserId(userId);
                List<DoEvent> doEvents = doEventService.getDoEventByUserDate(doEvent);
                for (DoEvent doe : doEvents) {
                    doe.setFinalResult(doe.getResult());
                    doEventService.updateDovent1(doe);
                    logger.info("===initialDelay:重置打卡finalResult");
                }
                if (week == "星期一" || week == "星期三" || week == "星期五") {
                    updateFinalResult(doEvent,event);
                } else {
                    updateFinalResult(doEvent,event1);
                }

            } catch (Exception e) {
                logger.info("===initialDelay: 未找到相应数据");
            }
        }
    }

    @Scheduled(cron = "0 0 22 ? * MON,WED,FRI,SAT,SUN")
    public void updateAbility() throws Exception {
        List<Integer> userIdList = abilityService.getAllUserId();
        logger.info("===initialDelay: userIdList is " + userIdList);
        for (Integer userId : userIdList) {
            List<DoEvent> doEventList = doEventService.getDoEventByUserId(userId);
            Integer sum = doEventList.size();
            logger.info("===initialDelay: sum is " + sum);
            List<DoEvent> doEvents = null;
            for (DoEvent doEvent : doEventList) {
                if (doEvents == null) {
                    doEvents = new ArrayList<DoEvent>();
                }
                if (doEvent.getResult() == 1) {
                    doEvents.add(doEvent);
                }
            }
            Integer num = doEvents.size();
            logger.info("===initialDelay: num is " + num);
            double proportion = (double) num / sum * 100;
            logger.info("===initialDelay: proportion is " + proportion);
            Ability ability = new Ability();
            ability.setUserId(userId);
            ability.setPerformAbility(proportion);
            ability.setCredibility(proportion);
            abilityService.updateAbility(ability);
        }
    }

    @Scheduled(cron = "0 0 23 ? * SUN")
    public void getDoEventByDate() throws Exception{
        EmailUtil emailUtil=new EmailUtil();
        List<List<DoEvent1>> clazzList=null;
        StringBuilder stringBuilder=new StringBuilder();
        List<Clazz> clazzes=clazzService.getAllClazz();
        logger.info("===initialDelay: clazzes is " + clazzes);
        for(Clazz clazz:clazzes){
            List<User> users=userService.getUserByClazzId(clazz.getId());
            logger.info("===initialDelay: users is " + users);
            for(User user:users){
                List<DoEvent1> doEvent1s=null;
                List<DoEvent> doEvents=doEventService.getAWeekDoEventByUserId(user);
                logger.info("===initialDelay: doEvents is " + doEvents);
                for(DoEvent doEvent:doEvents){
                    if(doEvent1s==null){
                        doEvent1s=new ArrayList<DoEvent1>();
                    }
                    if(clazzList==null){
                        clazzList=new ArrayList<List<DoEvent1>>();
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sdf.format(doEvent.getDate());
                    DoEvent1 doEvent1=new DoEvent1();
                    doEvent1.setDate(date);
                    doEvent1.setEvent(eventService.getEventById1(doEvent.getEventId()).getName());
                    doEvent1.setUserName(user.getName());
                    if(doEvent.getResult()==1){
                        doEvent1.setResult("已打卡");
                    }else {
                        if(doEvent.getResult()==0){
                            doEvent1.setResult("未及格");
                        }
                        doEvent1.setResult("未打卡");
                    }
                    if(doEvent.getFinalResult()==1){
                        doEvent1.setFinalResult("打卡成功");
                    }else {
                        if(doEvent.getFinalResult()==0){
                            doEvent1.setFinalResult("取消勤学金资格");
                        }else {
                            doEvent1.setFinalResult("打卡失败");
                        }
                    }
                    logger.info("===initialDelay: doEvent1 is " + doEvent1);
                    doEvent1s.add(doEvent1);
                    clazzList.add(doEvent1s);
                }
                logger.info("===initialDelay: doEvent1s is " + doEvent1s);

                if("teacher".equals(user.getType())){
                    continue;
                }
                String str=String.valueOf(listToTable(doEvent1s));
                logger.info("===initialDelay:str is "+str);
                emailUtil.sendEmail(user.getEmail(),str,user.getName());
            }
            continue;
        }
        logger.info("===initialDelay: clazzList is " + clazzList);
        for(List<DoEvent1> list:clazzList){
            stringBuilder.append(listToTable(list));
        }
        String str1=String.valueOf(stringBuilder);
        emailUtil.sendEmail("1010373871@qq.com",str1,"zzty");
    }

    private void updateFinalResult(DoEvent doEvent, String[] event){
        for (int i = 0; i < event.length; i++) {
            logger.info("===initialDelay: event is " + event[i]);
            Integer eventId = eventService.getEventIdByName(event[i]);
            logger.info("===initialDelay: eventId is " + eventId);
            doEvent.setEventId(eventId);
            DoEvent doEvent1 = doEventService.getDoEvent(doEvent);
            if (doEvent1.getResult() == -1) {
                doEvent1.setFinalResult(0);
                doEventService.updateDovent(doEvent1);
                logger.info("===initialDelay:重置打卡finalResult，取消今日勤学金资格");
                break;
            }
        }
    }

    private StringBuilder listToTable(List<DoEvent1> doEvent1s){
        if(doEvent1s==null){
            doEvent1s=new ArrayList<DoEvent1>();
        }
        StringBuilder str=new StringBuilder();
        for(DoEvent1 doEvent1:doEvent1s){
            str.append("<tr><td align='center'>"+doEvent1.getUserName()+"</td><td align='center'>"+doEvent1.getDate() +"</td><td align='center'>"
                    +doEvent1.getEvent() +"</td><td align='center'>"+doEvent1.getResult()+"</td><td align='center'>"+doEvent1.getFinalResult()+"</td></tr>");

        }
       return str;
    }
}
